package droid.ru;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper {
		
	// The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/RuDroid/databases/";
    // The database nam
    private static String DB_NAME = "rudb";
    // Database object
    private SQLiteDatabase myDataBase; 
    // Context
    private final Context myContext;
    // DB tables and columns
    private static final String MENU_TABLE = "menu";
    private static final String LAST_ACCESS_TABLE = "last_access";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_ITEM = "food";
    private static final String COLUMN_YEAR = "year";
    private static final String COLUMN_MONTH = "month";
    private static final String COLUMN_DAY = "day";
    
    
    /*// Global attributes
	private static final String DATABASE_NAME = "myDatabase.db";
	private static final String DATABASE_TABLE = "contact";
	private static final String DATABASE_CREATE =
	"create table " + DATABASE_TABLE +
	" ( _id INTEGER PRIMARY KEY AUTOINCREMENT," +
	"name TEXT UNIQUE, mail TEXT, phone TEXT);";
	private static final String COLUMN_NAME = "name";
	private static final String COLUMN_MAIL = "mail";
	private static final String COLUMN_PHONE = "phone";	
	private static final String KEY_ID = "_id";*/
	
	
	/**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
	public DbHelper(Context context) {
		super(context, DB_NAME, null, 1);
		this.myContext = context;
	}
	
	/**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{
     	 
    	if(checkDataBase()){
    		//do nothing - database already exist
    	}
    	else { 
    		//By calling this method and empty database will be created into the default system path
               //of your application so we are going to be able to overwrite that database with our database.
        	this.getReadableDatabase();
 
        	try {
     			copyDataBase(); 
    		} 
        	catch (IOException e) { 
        		throw new Error("Error copying database"); 
        	}
    	}
 
    }
    
    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
	private boolean checkDataBase() {

		SQLiteDatabase checkDB = null;

		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);
		} catch (SQLiteException e) {
			// database does't exist yet.
		}

		if (checkDB != null) {
			checkDB.close();
		}

		return checkDB != null ? true : false;
	}
	
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException {
 
    	//Open your local db as the input stream
    	InputStream myInput = myContext.getAssets().open(DB_NAME);
 
    	// Path to the just created empty db
    	String outFileName = DB_PATH + DB_NAME;
 
    	//Open the empty db as the output stream
    	OutputStream myOutput = new FileOutputStream(outFileName);
 
    	//transfer bytes from the inputfile to the outputfile
    	byte[] buffer = new byte[1024];
    	int length;
    	while ((length = myInput.read(buffer))>0){
    		myOutput.write(buffer, 0, length);
    	}
 
    	//Close the streams
    	myOutput.flush();
    	myOutput.close();
    	myInput.close();
 
    }	 
	
	public void openDataBase() throws SQLException{
		 
    	//Open the database
        String myPath = DB_PATH + DB_NAME;
    	myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 
    }
	
	@Override
	public synchronized void close() {
 
    	    if(myDataBase != null)
    		    myDataBase.close();
 
    	    super.close();
 
	}
 
	@Override
	public void onCreate(SQLiteDatabase db) {
 
	}
 
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
	}
	   
	
	public boolean menuUpToDate()
	{
		boolean ret = false;
		
		try {
			String[] result_columns = new String[] { COLUMN_YEAR, COLUMN_MONTH, COLUMN_DAY };
			Cursor row = myDataBase.query(true, LAST_ACCESS_TABLE, result_columns, null, null, null, null, null, null);
			
			if(row.moveToFirst()) {
				int year = row.getInt(0);
				int month = row.getInt(1);
				int day = row.getInt(2);
				Date dbDate = new Date(year, month, day);
				ret = DateUtils.dateIsUpToDate(dbDate);
			}
			else {
				ret = false;
			}
			 
				
		}
		catch(Exception e) {
			
		}
		
		return ret;
	}
	
	/*public void insert(String _name, String _mail, String _phone) {
		try {			
			if(!_name.contentEquals("")) 
			{								
				ContentValues cv = new ContentValues();
				cv.put(COLUMN_NAME, _name);
				cv.put(COLUMN_MAIL, _mail);
				cv.put(COLUMN_PHONE, _phone);
				myDataBase.insert(DATABASE_TABLE, null, cv);
			}
		} 
		catch (Exception e) {
			System.out.println("EXCEPTION: " + e.getMessage());
			e.printStackTrace();
		}
	}*/
    /*public void count() {
    	try {
			ArrayList<Contact> list = new ArrayList<Contact>();
			String[] result_columns = new String[] {KEY_ID, COLUMN_NAME, COLUMN_MAIL, COLUMN_PHONE};
			Cursor rows = db.query(true, DATABASE_TABLE, result_columns, null, null, null, null, null, null);
			
			if(rows.moveToFirst()) {
				do {
					int id = rows.getInt(0);
			    	String name = rows.getString(1);
			    	String mail = rows.getString(2);
			    	String phone = rows.getString(3);
			    	Contact ct = new Contact();
			    	ct.setName(name);
			    	ct.setMail(mail);
			    	ct.setPhone(phone);
			    	list.add(ct);
				} while(rows.moveToNext());
			}
			
			
			CharSequence text = "Num of rows: " + list.size();
			int duration = Toast.LENGTH_SHORT;

			Toast toast = Toast.makeText(this.context, text, duration);
			toast.show();
		} 
    	catch (Exception e) {
			System.out.println("EXCEPTION: " + e.getMessage());
			e.printStackTrace();
		}		
	}*/
    
    /*public void delete(String name) {
    	try {
			if(!name.contentEquals(""))
			{
				myDataBase.delete(DATABASE_TABLE, COLUMN_NAME + " = '" + name + "'", null);								
			}			
			
		} catch (Exception e) {
			System.out.println("EXCEPTION: " + e.getMessage());
			e.printStackTrace();
		}
    }	*/
}

